<template>
    <div class="cnfxPieChart">
        <div ref="chartRef" style="width: 100%; height: 100%;"></div>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import * as echarts from 'echarts/core';
import { TooltipComponent, LegendComponent } from 'echarts/components';
import { PieChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';

// 注册必需组件
echarts.use([TooltipComponent, LegendComponent, PieChart, CanvasRenderer]);

const props = defineProps({
    data: {
        type: Array,
        default: () => []
    },
    title: {
        type: String,
        default: '产能分析'
    },
    valueKey: {
        type: String,
        default: 'value'
    },
    nameKey: {
        type: String,
        default: 'name'
    }
});

const chartRef = ref(null);
let chartInstance = null;

const initChart = () => {
    chartInstance = echarts.init(chartRef.value);

    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            show: false,
        },
        series: [{
            name: props.title,
            type: 'pie',
            radius: ['50%', '90%'],
            avoidLabelOverlap: false,
            itemStyle: {
                color: function (params) {
                    return params.data.background
                }
            },
            label: {
                show: false,
                position: 'center',
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: 16,
                    fontWeight: 'bold',
                    color: '#fff'
                },
            },
            labelLine: {
                show: false
            },
            data: props.data.map(item => ({
                value: item[props.valueKey],
                name: item[props.nameKey],
                background: item.background
            }))
        }]
    };

    chartInstance.setOption(option);
};

const resizeHandler = () => {
    chartInstance?.resize();
};

onMounted(() => {
    initChart();
    window.addEventListener('resize', resizeHandler);
});

onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeHandler);
    chartInstance?.dispose();
});

watch(() => props.data, (newVal) => {
    chartInstance?.setOption({
        series: [{
            data: newVal.map(item => ({
                value: item[props.valueKey],
                name: item[props.nameKey],
                background: item.background,
                itemStyle: { color: item.background } // 确保颜色配置同步更新
            }))
        }]
    });
    chartInstance?.resize();
}, { deep: true, immediate: true }); // 添加immediate参数立即生效
</script>

<style scoped lang="scss">
.cnfxPieChart {
    width: 100%;
    height: 100%;
}
</style>